/*
 * @Author: TT-hzy
 * @Date: 2024-06-27 17:41:40
 * @LastEditors: TT-hzy 
 * @LastEditTime: 2024-07-05 12:00:04
 * @Description:
 */

import { Controller } from "egg";


export default class UserController extends Controller {
  // 获取用户列表
  async index() {
    const ctx = this.ctx;
    /// Get  query
    /// POST  params
    const query = {
      limit: ctx.helper.parseInt(ctx.query.limit) || 10,
      offset: ctx.helper.parseInt(ctx.query.offset) || 0,
    };
    console.log(query);
    ctx.body = await ctx.service.user.list(query);
  }

  // 获取用户详情
  async findUser() {
    const ctx = this.ctx;

    let name = ctx.query.name;
    let password = ctx.query.password;
    if (name == null || password == null) {
      return (ctx.body = ctx.fail({ msg: "用户名或密码不能为空" }));
    }

    const res = await ctx.service.common.getUserInfoByNameAndPassword(ctx.query.name, ctx.query.password);
    if (res == null) {
      return ctx.configReturnBody({
        ctx,
        isOk: false,
        msg: "用户名或密码错误"
      })

    }
    var data = res.toJSON();
    data.createdAt = ctx.helper.relativeTimeRounding(res.createdAt);
    data.updatedAt = ctx.helper.relativeTimeRounding(res.updatedAt);
    ctx.body = ctx.success({
      data: data
    });
  }
  // 添加用户
  async register() {
    const ctx = this.ctx;
    let parmas = ctx.request.body;
    let msg = this.verifyRegistrationParameters(parmas);
    if (msg != '') {
      return (ctx.body = ctx.fail({ msg: msg }));
    }
    const user = await ctx.service.common.getUserInfoByNameAndPassword(parmas.name, parmas.password);
    if (user != null) {
      return this.configLoginSuccessOrFail({ msg: "用户已存在" });
    }
    const data = await ctx.service.user.register(parmas,);
    return this.configLoginSuccessOrFail({ data, isLogin: false });
  }
  // 登录
  async login() {
    const {
      ctx,
      service
    } = this;
    let parmas = ctx.request.body;
    let msg = this.verifyRegistrationParameters(parmas);
    if (msg != '') {
      return (ctx.body = ctx.fail({ msg: msg }));
    }

    var data = await ctx.service.user.login(ctx.request.body);
    var userInfo: any;

    if (data != null) {
      userInfo = data.dataValues;
      let token = await service.actionToken.createToken(userInfo);
      msg = "登录成功";
      userInfo.token = token;
    } else {
      msg = "用户名或密码错误";
    }
    return this.configLoginSuccessOrFail({
      data: userInfo,
      msg: msg,
    });
  }

  /// 更新用户信息
  async updateUserInfo() {
    const {
      ctx
    } = this;
    const tokenUserInfo = await ctx.service.actionToken.getTokenInfo();
    if (tokenUserInfo == null) {
      return ctx.configReturnBody({
        ctx,
        isOk: false,
        msg: "用户未登录"
      });
    } else {

      const user = await ctx.service.common.getUserInfoByPk(tokenUserInfo.id);
      if (user == null) {
        return ctx.configReturnBody({
          ctx,
          isOk: false,
          msg: "用户不存在"
        });
      }
      var userInfo = {};
      const data = await ctx.service.user.update({ id: tokenUserInfo.id, updates: ctx.request.body });
      if (data == 1) {
        userInfo = await ctx.service.common.getUserInfoByPk(tokenUserInfo.id).then(res => res!.dataValues);
      }
      return ctx.configReturnBody({
        ctx,
        isOk: data == 1 ? true : false,
        data: userInfo,
        msg: data == 1 ? "更新成功" : "更新失败"
      });
    }

  }

  configLoginSuccessOrFail({
    data,
    isLogin = true,
    msg,
  }: {
    data?: any,
    isLogin?: boolean,
    msg?: string
  }) {
    var isOk = data != null;
    var typeMsg = isLogin ? "登录" : "注册";
    var msgA = isOk ? "成功" : "失败";
    return this.ctx.configReturnBody({
      ctx: this.ctx,
      isOk,
      data,
      msg: msg || typeMsg + msgA,

    });
  }
  // 注册用户参数验证
  verifyRegistrationParameters(params: any) {
    var msg = "";
    if (!params.name) {
      msg = "用户名不能为空";
    }
    if (params.password == null || params.password === "") {
      msg = "密码不能为空";
    }

    return msg;
  }
}
